#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

void print_msg(char * msg){
	printf("msg: %c%c%c%c\n",msg[0], msg[1], msg[2], msg[3]);
	if(msg[0] != '1' || msg[3] != '4'){
		printf("it's wrong!\n");
	}
}
void test(char * buf, int size){
	static char remain[4] = {0};
	static int remain_len = 0;
	int buf_idx = 0;
	if(remain_len > 0){
		while(remain_len < 4 && buf_idx < size){
			remain[remain_len++] = buf[buf_idx++];
		}
		if(remain_len >= 4){
			print_msg(remain);
			remain_len = 0;
		}
	}
	while(size - buf_idx > 3){
		print_msg(&buf[buf_idx]);
		buf_idx += 4;
	}
	if(buf_idx < size){
		remain_len = size-buf_idx;
		memcpy(remain, &buf[buf_idx], remain_len);
	}
}

int main(){
	char str[] = "1234";
	int index = 0;
	for(int i=0;i<500; i++){
		srand(i);
		int len = rand()%50;
		char  buf[50] = {0};
		int idx = index%4;
		index += len;
		for(int j=0; j<len; j++){
			buf[j] = str[idx++];
			idx = idx%4;
		}
		printf("_____________%d test %d char_________\n", i, len);
		test(buf, len);
		usleep(1000);
	}
	return 0;
}
